package com.geen.tuoke.ui.fragment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.FileUtils
import com.bumptech.glide.Glide
import com.geen.tuoke.R
import com.geen.tuoke.base.BaseFragment
import com.geen.tuoke.bean.MenuCode
import com.geen.tuoke.databinding.FragmentMeBinding
import com.geen.tuoke.network.utils.CacheUtil
import com.geen.tuoke.ui.activity.LoginActivity
import com.geen.tuoke.ui.activity.WebActivity
import com.geen.tuoke.ui.adapter.MenuItemAdapter
import com.geen.tuoke.ui.dialog.DialogCustom
import com.geen.tuoke.ui.dialog.DialogRecharge
import com.geen.tuoke.ui.dialog.DialogUpdate
import com.geen.tuoke.ui.viewmodel.MainViewModel
import com.geen.tuoke.ui.viewmodel.MeViewModel
import com.geen.tuoke.utils.AppManager
import com.geen.tuoke.utils.IntentConstants
import com.geen.tuoke.utils.LogUtils
import com.geen.tuoke.utils.ext.checkAppPermission
import com.geen.tuoke.utils.ext.showBottomSheetList
import com.geen.tuoke.utils.ext.startActivity
import com.geen.tuoke.utils.ext.toastShort
import com.kbeanie.multipicker.api.CacheLocation
import com.kbeanie.multipicker.api.CameraImagePicker
import com.kbeanie.multipicker.api.ImagePicker
import com.kbeanie.multipicker.api.Picker
import com.kbeanie.multipicker.api.callbacks.ImagePickerCallback
import com.kbeanie.multipicker.api.entity.ChosenImage
import com.seeway.wms.utils.ext.showTipDialogExt
import com.seeway.wms.utils.ext.showTipsDialog
import kotlinx.android.synthetic.main.fragment_me.view.*
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.util.jar.Manifest


/**
 * @Author LuoJi
 * @Date 2021/12/23-15:27
 * @Desc
 */
class FragmentMe : BaseFragment<MeViewModel, FragmentMeBinding>(),MeViewModel.MeHandler,ImagePickerCallback {
    private val mainViewModel by activityViewModels<MainViewModel>()
    private lateinit var mAdapter : MenuItemAdapter
    private var imagePicker : ImagePicker? = null
    private var cameraPicker: CameraImagePicker? = null
    private var pickerPath:String = ""
    override fun getLayoutId(): Int {
        return R.layout.fragment_me
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        with(mBinding){
            viewModel = mViewModel
            lifecycleOwner = this@FragmentMe
            handler = this@FragmentMe
        }
        initAdapter()

        mViewModel.uploadAvatarSuccess.observe(viewLifecycleOwner,{
            if(it.isNotEmpty()){
                Glide.with(context!!.applicationContext)
                        .load(it.toString())
                        .into(mBinding.ivAvatar)
                //上传成功，删除拍照目录
                val avatarFile = context!!.applicationContext.getExternalFilesDir("").toString()+"/"+"Pictures"
                FileUtils.deleteAllInDir(avatarFile)
            }
        })
    }

    private fun initAdapter(){
        mAdapter = MenuItemAdapter()
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val menuItem = mAdapter.getItem(position)
            when(menuItem.menuCode){
                MenuCode.版本更新.ordinal -> {
                    DialogUpdate(requireContext()).showDialog()
                }
                MenuCode.话费充值.ordinal -> {
                    //检查金额列表是否为空
                    if(mViewModel.payMoneyList.value.isNullOrEmpty()){
                        //请求
                        mViewModel.getPayMoneyList()
                        return@setOnItemClickListener
                    }
                    DialogRecharge(requireContext(),mViewModel.payMoneyList.value!!, rechargeCallBack = {
                        toastShort(it.money)
                    }).showDialog()
                }
                MenuCode.客服服务.ordinal -> {
                    DialogCustom(requireContext()).showDialog()
                }
                MenuCode.用户协议.ordinal -> {
                    startActivity<WebActivity>(
                        Pair(
                            IntentConstants.INTENT_URL,
                            "https://www.baidu.com"
                        ),
                        Pair(IntentConstants.INTENT_TITLE, "用户协议")
                    )
                }
                MenuCode.隐私政策.ordinal -> {
                    startActivity<WebActivity>(
                        Pair(
                            IntentConstants.INTENT_URL,
                            "https://www.baidu.com"
                        ), Pair(IntentConstants.INTENT_TITLE, "隐私政策")
                    )
                }
            }

        }
        mAdapter.data = mViewModel.menuItemList

        mBinding.mRecycleView.adapter = mAdapter
    }

    override fun loginOut(view: View) {
        showTipsDialog(message = "确定退出登陆吗？",yes = {
            CacheUtil.clearCache()
            AppManager.appManager?.finishAllActivity()
            startActivity<LoginActivity>()
        })
    }

    override fun clickPhoto(view: View) {
        val listItem = mutableListOf<String>()
        listItem.add("拍照")
        listItem.add("选择")
        showBottomSheetList(itemList = listItem, callBack = {
            when (it) {
                0 -> {
                    checkAppPermission(android.Manifest.permission.CAMERA,callBack = {
                        takePicture()
                    })
                }
                1 -> {
                    pickImageSingle()
                }
            }
        })
    }

    override fun onImagesChosen(p0: MutableList<ChosenImage>?) {
        p0?.let {
            val file = File(it[0].thumbnailSmallPath)
            Luban.with(context)
                .load(file)
                .ignoreBy(100) // 忽略不压缩图片的大小
                .setTargetDir(context?.applicationContext?.getExternalFilesDir("").toString()) // 设置压缩后文件存储位置
                .setCompressListener(object : OnCompressListener {
                    //设置回调
                    override fun onStart() {
                    }
                    override fun onSuccess(file: File?) {
                        mViewModel.uploadAvatar(file!!)
                    }
                    override fun onError(e: Throwable) {

                    }
                }).launch() //启动压缩
        }
    }

    private fun pickImageSingle() {
        imagePicker = ImagePicker(this).apply {
            shouldGenerateMetadata(true)
            shouldGenerateThumbnails(true)
            setImagePickerCallback(this@FragmentMe)
            pickImage()
        }
    }

    private fun takePicture() {
        cameraPicker = CameraImagePicker(this)
        cameraPicker!!.setCacheLocation(CacheLocation.EXTERNAL_STORAGE_APP_DIR)
        cameraPicker!!.shouldGenerateMetadata(true)
        cameraPicker!!.shouldGenerateThumbnails(true)
        cameraPicker!!.setImagePickerCallback(this)
        pickerPath = cameraPicker!!.pickImage()

        LogUtils.debugInfo("文件地址"+pickerPath)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Picker.PICK_IMAGE_DEVICE) {
                if (imagePicker == null) {
                    imagePicker = ImagePicker(this)
                    imagePicker!!.setImagePickerCallback(this)
                }
                imagePicker!!.submit(data)
            } else if (requestCode == Picker.PICK_IMAGE_CAMERA) {
                if (cameraPicker == null) {
                    cameraPicker = CameraImagePicker(this)
                    cameraPicker!!.setImagePickerCallback(this)
                    cameraPicker!!.reinitialize(pickerPath)
                }
                cameraPicker!!.submit(data)
            }
        }
    }

    override fun onError(p0: String?) {

    }

    override fun onResume() {
        super.onResume()
        if(mViewModel.userInfo.value==null){
            mViewModel.userInfo.value = CacheUtil.getUserInfo()
            mViewModel.reloadUserInfo()
        }
    }

    override fun onLazyLoad() {
        super.onLazyLoad()
        mViewModel.getPayMoneyList()
        mViewModel.userInfo.value = CacheUtil.getUserInfo()
        mViewModel.reloadUserInfo()
    }
}